package com.leetcode.algorithm.y22.m08.w1;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;

/**
 * 636. 函数的独占时间
 * 
 * https://leetcode.cn/problems/exclusive-time-of-functions/
 * 
 * @author jie.deng
 *
 */
class Question0636Solution01 {

	public int[] exclusiveTime(int n, List<String> logs) {
		int[] exclusiveTimeArr = new int[n];
		Deque<int[]> stack = new ArrayDeque<>();
		for (String log : logs) {
			String[] logStrs = log.split(":");
			int functionId = Integer.parseInt(logStrs[0]);
			int timestamp = Integer.parseInt(logStrs[2]);
			if ("start".equals(logStrs[1])) {
				stack.push(new int[] { functionId, timestamp, 0 });
			} else {
				int[] functionArr = stack.poll();
				assert functionArr[0] == functionId;
				int exclusiveTime = timestamp - functionArr[1] + 1;
				exclusiveTimeArr[functionId] += (exclusiveTime - functionArr[2]);

				if (!stack.isEmpty()) {
					int[] prevFunctionArr = stack.peek();
					prevFunctionArr[2] += exclusiveTime;
				}
			}
		}
		return exclusiveTimeArr;
	}

}